package com.api.shopapi.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.api.shopapi.entity.*;
import com.api.shopapi.entity.dto.*;
import com.api.shopapi.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 老人
 * */

@RequestMapping("Elderly")
@RestController
public class ElderlyController extends BaseController {

    @Autowired
    @Qualifier("ElderlyServiceImplOne")
    private ElderlyService elderlyService;

    @Autowired
    @Qualifier("StaffServiceImplOne")
    private StaffService staffService;

    @Autowired
    @Qualifier("UserServiceImplOne")
    private UserService userService;

    @Autowired
    @Qualifier("AreaServiceImplOne")
    private AreaService areaService;

    @Autowired
    @Qualifier("RechargeServiceImplOne")
    private RechargeService rechargeService;

    @Autowired
    @Qualifier("OrderServiceImplOne")
    private OrderService orderService;

    @Autowired
    @Qualifier("ZoneServiceImplOne")
    private ZoneService zoneService;

    @Autowired
    @Qualifier("SysNationServiceImplOne")
    private SysNationService sysNationService;

    @Autowired
    @Qualifier("ElderlyClassServiceImplOne")
    private ElderlyClassService elderlyClassService;

    @Autowired
    @Qualifier("CardStatusServiceImplOne")
    private CardStatusService cardStatusService;


    @Autowired
    @Qualifier("CardRecordServiceImplOne")
    private CardRecordService cardRecordService;

    @Autowired
    @Qualifier("SeatsServiceImplOne")
    private SeatsService seatsService;

    @Autowired
    @Qualifier("ElderlyClockinServiceImplOne")
    private ElderlyClockinService elderlyClockinService;

    @Autowired
    @Qualifier("ElderlyMonthlyReportServiceImplOne")
    private ElderlyMonthlyReportService elderlyMonthlyReportService;

    @Autowired
    @Qualifier("ElderlyClockinMonthServiceImplOne")
    private ElderlyClockinMonthService elderlyClockinMonthService;

    @Autowired
    @Qualifier("ServeServiceImplOne")
    private ServeService serveService;


    @Autowired
    @Qualifier("InstitutionStaffRelServiceImplOne")
    private InstitutionStaffRelService institutionStaffRelService;


    @Autowired
    @Qualifier("MedicinerServiceImplOne")
    private MedicinerService medicinerService;

    @Autowired
    @Qualifier("MedicinerStaffRelServiceImplOne")
    private MedicinerStaffRelService medicinerStaffRelService;


    @Autowired
    @Qualifier("NurseServiceImplOne")
    private NurseService nurseService;

    @Autowired
    @Qualifier("NurseStaffRelServiceImplOne")
    private NurseStaffRelService nurseStaffRelService;


    @Autowired
    @Qualifier("DiseaseTypeServiceImplOne")
    private DiseaseTypeService diseaseTypeService;

    @Autowired
    @Qualifier("ElderlyDiseaseTypeRelServiceImplOne")
    private ElderlyDiseaseTypeRelService elderlyDiseaseTypeRelService;


    @Autowired
    @Qualifier("UserFaceServiceImplOne")
    private UserFaceService userFaceService;


    @Autowired
    @Qualifier("InstitutionServiceImplOne")
    private InstitutionService institutionService;


    @Autowired
    @Qualifier("ElderlyCheckinAssessWaitServiceImplOne")
    private ElderlyCheckinAssessWaitService elderlyCheckinAssessWaitService;



    //ins
    @RequestMapping(value = "InsDelete", method = RequestMethod.POST)
    public MyResult InsDelete(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Mediciner/InsDelete");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String institutionCode = institutionStaffRel.getInstitutionCode();

            List<Elderly> list = elderlyService.listByInsCode(institutionCode);
            for(Elderly elderly:list){

                elderlyService.delete(elderly.getElderlyCode());

            }


            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        }  catch (Exception e) {
            insertError("/Mediciner/InsDelete", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }

    }



    //获取老人信息
    @RequestMapping(value = "GetInfo", method = RequestMethod.POST)
    public MyResult GetInfo(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/PageByNotCheckin");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Elderly elderly = elderlyService.getByUserCode(userCode);

            return success(elderly);
        } catch (Exception e) {
            insertError("/Elderly/PageByNotCheckin", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //查询未签约的病患
    @RequestMapping(value = "PageByNotCheckin", method = RequestMethod.POST)
    public MyResult PageByNotCheckin(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageByNotCheckin");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String insCode = institutionStaffRel.getInstitutionCode();

            PageInfo<Elderly> pageInfo = elderlyService.pageByInsCodeCheckinStatus(pageIndex, pageSize,insCode, name, phone,0);

            List<ElderlyDTO> listDTO = new ArrayList<>();
            for(Elderly elderly:pageInfo.getList()){

                elderly = elderlyService.getByElderlyCode(elderly.getElderlyCode());
                ElderlyDTO dto = mapper.map(elderly,ElderlyDTO.class);

                listDTO.add(dto);
            }

            pageInfo.setList(Collections.unmodifiableList(listDTO));

            return success(pageInfo);
        } catch (Exception e) {
            insertError("/Elderly/PageByNotCheckin", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //机构 所有
    @RequestMapping(value = "InsPage", method = RequestMethod.POST)
    public MyResult InsPage(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            int status = jsonObject.getInteger("status");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            String zoneCode = jsonObject.getString("zoneCode");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String insCode = institutionStaffRel.getInstitutionCode();

            PageInfo<ElderlyDTO> pageInfo = elderlyService.pageByInsCode(pageIndex, pageSize,
                    insCode, name, phone,status,zoneCode);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }
    @RequestMapping(value = "InsPageByInsCode", method = RequestMethod.POST)
    public MyResult InsPageByInsCode(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String institutionCode = jsonObject.getString("institutionCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            PageInfo<ElderlyDTO> pageInfo = elderlyService.pageByInsCode(pageIndex, pageSize,
                    institutionCode, "", "",-1,"");

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //机构 已签约
    @RequestMapping(value = "InsPageCheckin", method = RequestMethod.POST)
    public MyResult InsPageCheckin(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            int checkinStatus = jsonObject.getInteger("checkinStatus");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String insCode = institutionStaffRel.getInstitutionCode();

            PageInfo<Elderly> pageInfo = elderlyService.pageByInsCodeCheckinStatus(pageIndex, pageSize,
                    insCode, name, phone,checkinStatus);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //机构查看申请中的
    @RequestMapping(value = "InsPageApply", method = RequestMethod.POST)
    public MyResult InsPageApply(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String insCode = institutionStaffRel.getInstitutionCode();

            PageInfo<Elderly> pageInfo = elderlyService.pageByInsCodeApplyStatus(pageIndex, pageSize,
                    insCode, name, phone,1);

            List<Elderly> list = new ArrayList<>();
            for(Elderly elderly:pageInfo.getList()){
                elderly = elderlyService.getByElderlyCode(elderly.getElderlyCode());
                list.add(elderly);
            }

            pageInfo.setList(Collections.unmodifiableList(list));


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "InsPageApplyStatus", method = RequestMethod.POST)
    public MyResult InsPageApplyStatus(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            int applyStatus= jsonObject.getInteger("applyStatus");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String insCode = institutionStaffRel.getInstitutionCode();

            PageInfo<Elderly> pageInfo = elderlyService.pageByInsCodeApplyStatus(pageIndex, pageSize,
                    insCode, name, phone,applyStatus);

            List<Elderly> list = new ArrayList<>();
            for(Elderly elderly:pageInfo.getList()){
                elderly = elderlyService.getByElderlyCode(elderly.getElderlyCode());
                list.add(elderly);
            }

            pageInfo.setList(Collections.unmodifiableList(list));


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //机构通过申请
    @RequestMapping(value = "InsPassApply", method = RequestMethod.POST)
    public MyResult InsPassApply(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String elderlyCode = jsonObject.getString("elderlyCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);
            elderly.setApplyStatus(2);
            elderlyService.update(elderly);

            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //机构驳回申请
    @RequestMapping(value = "InsRejectApply", method = RequestMethod.POST)
    public MyResult InsRejectApply(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String elderlyCode = jsonObject.getString("elderlyCode");
            String rejectMessage = jsonObject.getString("rejectMessage");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);
            elderly.setApplyStatus(3);
            elderly.setRejectMessage(rejectMessage);
            elderlyService.update(elderly);

            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //机构 已签约
    @RequestMapping(value = "InsPageApp", method = RequestMethod.POST)
    public MyResult InsPageApp(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/InsPageApp");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            User user = userService.getByUserCode(userCode);
            String institutionCode = user.getInstitutionCode();

            PageInfo<Elderly> pageInfo = elderlyService.pageByInsCodeCheckinStatus(pageIndex, pageSize,
                    institutionCode, name, phone,1);

            List<ElderlyDTO> listDTO = new ArrayList<>();
            for(Elderly elderly :pageInfo.getList()){

                elderly = elderlyService.getByElderlyCode(elderly.getElderlyCode());
                ElderlyDTO elderlyDTO = mapper.map(elderly,ElderlyDTO.class);
                UserFace userFace = userFaceService.getByUserCode(elderlyDTO.getUserCode());
                if(userFace == null){
                    elderlyDTO.setIsRegFace(false);
                }else{
                    elderlyDTO.setIsRegFace(true);
                }

                listDTO.add(elderlyDTO);
            }

            pageInfo.setList(Collections.unmodifiableList(listDTO));

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/InsPageApp", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //机构带病种
    @RequestMapping(value = "InsPageDiseaseType", method = RequestMethod.POST)
    public MyResult InsPageDiseaseType(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            int status = jsonObject.getInteger("status");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            String zoneCode = jsonObject.getString("zoneCode");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String insCode = institutionStaffRel.getInstitutionCode();

            PageInfo<ElderlyDTO> pageInfo = elderlyService.pageByInsCode(pageIndex, pageSize,
                    insCode, name, phone,status,zoneCode);

            for(ElderlyDTO elderlyDTO:pageInfo.getList()){

                List<ElderlyDiseaseTypeRel> list1 = elderlyDiseaseTypeRelService.ListByElderlyCode(elderlyDTO.getElderlyCode());
                List<ElderlyDiseaseTypeRelDTO> list2 = new ArrayList<>();
                for(ElderlyDiseaseTypeRel elderlyDiseaseTypeRel:list1){
                    ElderlyDiseaseTypeRelDTO dto = mapper.map(elderlyDiseaseTypeRel,ElderlyDiseaseTypeRelDTO.class);
                    DiseaseType diseaseType = diseaseTypeService.getByDiseaseTypeCode(dto.getDiseaseTypeCode());
                    dto.setDiseaseTypeName(diseaseType.getName());
                    list2.add(dto);
                }

                elderlyDTO.setListElderlyDiseaseTypeRelDTO(list2);

            }


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //政府 所有
    @RequestMapping(value = "GovPage", method = RequestMethod.POST)
    public MyResult GovPage(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            int status = jsonObject.getInteger("status");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");

            String zoneCode = jsonObject.getString("zoneCode");
            String institutionCode = jsonObject.getString("institutionCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            PageInfo<ElderlyDTO> pageInfo = elderlyService.pageByGovCode(pageIndex, pageSize,
                    staff.getGovernmentCode(), name, phone,status,zoneCode);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "GovPage2", method = RequestMethod.POST)
    public MyResult GovPage2(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            String name = jsonObject.getString("name");
            String institutionCode = jsonObject.getString("institutionCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            PageInfo<Elderly> pageInfo = elderlyService.pageByGovCodeInsCodeName(pageIndex, pageSize,
                    staff.getGovernmentCode(),institutionCode,name);

            List<ElderlyDTO> listDTO = new ArrayList<>();
            for(Elderly elderly:pageInfo.getList()){
                elderly = elderlyService.getByElderlyCode(elderly.getElderlyCode());
                ElderlyDTO elderlyDTO = mapper.map(elderly,ElderlyDTO.class);
                User user2 = userService.getByUserCode(elderly.getUserCode());
                elderlyDTO.setLoginName(user2.getLoginName());

                Institution institution = institutionService.getByInstitutionCode(elderly.getInstitutionCode());
                User user = userService.getByUserCode(institution.getUserCode());
                elderlyDTO.setInstitutionName(user.getName());

                listDTO.add(elderlyDTO);
            }
            pageInfo.setList(Collections.unmodifiableList(listDTO));


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //政府 已签约
    @RequestMapping(value = "GovPageCheckin", method = RequestMethod.POST)
    public MyResult GovPageCheckin(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            int checkinStatus = jsonObject.getInteger("checkinStatus");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            PageInfo<Elderly> pageInfo = elderlyService.pageByGovCodeCheckinStatus(pageIndex, pageSize,
                    staff.getGovernmentCode(), name, phone,checkinStatus);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //政府查看申请中的
    @RequestMapping(value = "GovPageApply", method = RequestMethod.POST)
    public MyResult GovPageApply(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);


            PageInfo<Elderly> pageInfo = elderlyService.pageByGovCodeApplyStatus(pageIndex, pageSize,
                    staff.getGovernmentCode(), name, phone,2);

            List<Elderly> list = new ArrayList<>();
            for(Elderly elderly:pageInfo.getList()){
                elderly = elderlyService.getByElderlyCode(elderly.getElderlyCode());
                list.add(elderly);
            }
            pageInfo.setList(Collections.unmodifiableList(list));

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "GovPageApplyStatus", method = RequestMethod.POST)
    public MyResult GovPageApplyStatus(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            int applyStatus = jsonObject.getInteger("applyStatus");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);


            PageInfo<Elderly> pageInfo = elderlyService.pageByGovCodeApplyStatus(pageIndex, pageSize,
                    staff.getGovernmentCode(), name, phone,applyStatus);

            List<Elderly> list = new ArrayList<>();
            for(Elderly elderly:pageInfo.getList()){
                elderly = elderlyService.getByElderlyCode(elderly.getElderlyCode());
                list.add(elderly);
            }
            pageInfo.setList(Collections.unmodifiableList(list));

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //政府通过申请
    @RequestMapping(value = "GovPassApply", method = RequestMethod.POST)
    public MyResult GovPassApply(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String elderlyCode = jsonObject.getString("elderlyCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);

            if(elderly.getApplyStatus() !=2){
                return failed("机构审核未通过");
            }

            elderly.setApplyStatus(4);
            elderlyService.update(elderly);


            //插入新的待评估
            ElderlyCheckinAssessWait elderlyCheckinAssessWait = new ElderlyCheckinAssessWait();
            elderlyCheckinAssessWait.setElderlyCheckinAssessWaitCode(UUID.randomUUID().toString());
            elderlyCheckinAssessWait.setElderlyCode(elderlyCode);
            elderlyCheckinAssessWait.setCreateTime(new Date());
            elderlyCheckinAssessWait.setInstitutionCode(elderly.getInstitutionCode());
            elderlyCheckinAssessWait.setGovernmentCode(elderly.getGovernmentCode());
            elderlyCheckinAssessWaitService.insert(elderlyCheckinAssessWait);


            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //政府驳回申请
    @RequestMapping(value = "GovRejectApply", method = RequestMethod.POST)
    public MyResult GovRejectApply(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String elderlyCode = jsonObject.getString("elderlyCode");
            String rejectMessage = jsonObject.getString("rejectMessage");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);

            if(elderly.getApplyStatus() !=2){
                return failed("机构审核未通过");
            }

            elderly.setApplyStatus(5);
            elderly.setRejectMessage(rejectMessage);
            elderlyService.update(elderly);

            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //医生
    @RequestMapping(value = "MedicinerPage", method = RequestMethod.POST)
    public MyResult MedicinerPage(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            int status = jsonObject.getInteger("status");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            String zoneCode = jsonObject.getString("zoneCode");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            MedicinerStaffRel medicinerStaffRel = medicinerStaffRelService.getByStaffCode(staffCode);
            String medicinerCode = medicinerStaffRel.getMedicinerCode();

            Mediciner mediciner = medicinerService.getByMedicinerCode(medicinerCode);
            String insCode = mediciner.getInstitutionCode();

            PageInfo<ElderlyDTO> pageInfo = elderlyService.pageByInsCode(pageIndex, pageSize,
                    insCode, name, phone,status,zoneCode);

            //double balanceAll = elderlyService.getListByElderly(staff.getGovernmentCode(), name, phone,status,zoneCode);

            JSONObject jsonObject1 = new JSONObject();
            //jsonObject1.put("balanceAll",balanceAll);
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //护士
    @RequestMapping(value = "NursePage", method = RequestMethod.POST)
    public MyResult NursePage(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            int status = jsonObject.getInteger("status");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            String zoneCode = jsonObject.getString("zoneCode");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForElderlyClassGov");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            NurseStaffRel nurseStaffRel = nurseStaffRelService.getByStaffCode(staffCode);
            String nurseCode = nurseStaffRel.getNurseCode();

            Nurse nurse = nurseService.getByNurseCode(nurseCode);
            String insCode = nurse.getInstitutionCode();

            PageInfo<ElderlyDTO> pageInfo = elderlyService.pageByInsCode(pageIndex, pageSize,
                    insCode, name, phone,status,zoneCode);

            //double balanceAll = elderlyService.getListByElderly(staff.getGovernmentCode(), name, phone,status,zoneCode);

            JSONObject jsonObject1 = new JSONObject();
            //jsonObject1.put("balanceAll",balanceAll);
            jsonObject1.put("pageInfo",pageInfo);

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PageForElderlyClassGov", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }



    //后台添加
    @RequestMapping(value = "AddSimple", method = RequestMethod.POST)
    @Transactional
    public MyResult AddSimple(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String areaCode = jsonObject.getString("areaCode");
            String zoneCode =jsonObject.getString("zoneCode");
            String lat = jsonObject.getString("lat");
            String lon = jsonObject.getString("lon");
            String idCard = jsonObject.getString("idCard");

            String phone = jsonObject.getString("phone");
            String homeAddress = jsonObject.getString("homeAddress");

            String name = jsonObject.getString("name");

            String elderlyClassCode = jsonObject.getString("elderlyClassCode");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/Add");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);

            InstitutionStaffRel institutionStaffRel = institutionStaffRelService.getByStaffCode(staffCode);
            String insCode = institutionStaffRel.getInstitutionCode();

            String elderlyCode = UUID.randomUUID().toString();
            String userCode = UUID.randomUUID().toString();


            Elderly elderly2 = elderlyService.getByIdCard(idCard);
            if (elderly2 != null) {
                return failed("该身份证号已注册！");
            }

            Elderly elderly = new Elderly();
            elderly.setElderlyCode(elderlyCode);
            elderly.setUserCode(userCode);

            if(areaCode==null||areaCode.equals("")){
                elderly.setAreaCode(null);
            }else {
                String areaName = getAreaName(areaCode, "");
                elderly.setAreaCode(areaCode);
                elderly.setAreaName(areaName);
            }

            if(zoneCode==null||zoneCode.equals("")){
                elderly.setZoneCode(null);
            }else {
                String zoneName = getZoneName(zoneCode,"");
                String zoneCodePath =getZoneCode(zoneCode,"");
                elderly.setZoneCode(zoneCode);
                elderly.setZoneName(zoneName);
                elderly.setZoneCodePath("," + zoneCodePath + ",");
            }

            elderly.setAreaCode(areaCode);

            elderly.setLat(lat);
            elderly.setLon(lon);
            elderly.setHomeAddress(homeAddress);

            if (idCard == null || idCard.equals("")) {
                elderly.setIdCard(null);
                elderly.setGender(0);
            } else {
                int gender = GetGender(idCard);
                int age = GetAge(idCard);
                Date birthday = GetBirthday(idCard);
                elderly.setGender(gender);
                elderly.setIdCard(idCard);
                elderly.setBirthday(birthday);
                elderly.setAge(age);
            }

            elderly.setPhone(phone);
            elderly.setName(name);
            elderly.setElderlyClassCode(elderlyClassCode);
            elderly.setCreateTime(new Date());
            elderly.setApplyStatus(4);
            elderly.setGovernmentCode(staff.getGovernmentCode());
            elderly.setInstitutionCode(insCode);
            elderlyService.insert(elderly);


            User user = new User();
            user.setUserCode(userCode);
            user.setPhone(phone.trim());
            user.setLoginName(idCard);
            user.setPassword(getMD5Str(phone.trim().substring(5, 11)));
            user.setName(name);
            user.setCreateTime(new Date());
            user.setStatus(1);
            user.setUserType(1);
            user.setGovernmentCode(staff.getGovernmentCode());
            user.setInstitutionCode(insCode);
            userService.insert(user);

            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);

        } catch (Exception e) {
            insertErrorForAffair("/Elderly/Add!",jsonObject,e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }
    }


    //App注册
    @RequestMapping(value = "RegFromApp", method = RequestMethod.POST)
    @Transactional
    public MyResult RegFromApp(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String loginName = jsonObject.getString("loginName").trim();
            String pwd = jsonObject.getString("pwd");
            String phone = jsonObject.getString("phone").trim();

            String governmentCode = "9d7bfed5-5b29-46a6-9f84-057414260669";

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/Add");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            User user = userService.getByLoginName(loginName);
            if(user != null){
                return failed("登陆账号已存在");
            }

            String elderlyCode = UUID.randomUUID().toString();
            String userCode = UUID.randomUUID().toString();

            Elderly elderly = new Elderly();
            elderly.setElderlyCode(elderlyCode);
            elderly.setUserCode(userCode);
            elderly.setPhone(phone);
            elderly.setName(phone);
            elderly.setCreateTime(new Date());
            elderly.setGovernmentCode(governmentCode);
            elderlyService.insert(elderly);

            user = new User();
            user.setUserCode(userCode);
            user.setPhone(phone);
            user.setLoginName(loginName);
            user.setPassword(getMD5Str(pwd));
            user.setName(phone);
            user.setCreateTime(new Date());
            user.setStatus(1);
            user.setUserType(1);
            user.setGovernmentCode(governmentCode);
            userService.insert(user);

            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);

        } catch (Exception e) {
            insertErrorForAffair("/Elderly/Add",jsonObject,e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }
    }

    //申请长护
    @RequestMapping(value = "ApplyApp", method = RequestMethod.POST)
    @Transactional
    public MyResult ApplyApp(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");


            String userCode = jsonObject.getString("userCode");

            String name = jsonObject.getString("name");
            String idCard = jsonObject.getString("idCard");
            String homeAddress = jsonObject.getString("homeAddress");

            String zoneCode =jsonObject.getString("zoneCode");
            String areaCode = jsonObject.getString("areaCode");
            String institutionCode = jsonObject.getString("institutionCode");


            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/Add");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            User user = userService.getByUserCode(userCode);

            if(!isIdCard(idCard)){
                return failed("身份证号错误");
            }

            Elderly elderly2 = elderlyService.getByIdCard(idCard);
            if (elderly2 != null) {
                return failed("该身份证号已注册");
            }

            Elderly elderly = elderlyService.getByUserCode(userCode);

            if(elderly.getApplyStatus() != 0){
                return failed("长护申请状态异常");
            }

            if(areaCode==null||areaCode.equals("")){
                elderly.setAreaCode(null);
            }else {
                String areaName = getAreaName(areaCode, "");
                elderly.setAreaCode(areaCode);
                elderly.setAreaName(areaName);
            }

            if(zoneCode==null||zoneCode.equals("")){
                elderly.setZoneCode(null);
            }else {
                String zoneName = getZoneName(zoneCode,"");
                String zoneCodePath =getZoneCode(zoneCode,"");
                elderly.setZoneCode(zoneCode);
                elderly.setZoneName(zoneName);
                elderly.setZoneCodePath("," + zoneCodePath + ",");
            }

            elderly.setAreaCode(areaCode);
            elderly.setHomeAddress(homeAddress);

            if (idCard == null || idCard.equals("")) {
                elderly.setIdCard(null);
                elderly.setGender(0);
            } else {
                int gender = GetGender(idCard);
                int age = GetAge(idCard);
                Date birthday = GetBirthday(idCard);
                elderly.setGender(gender);
                elderly.setIdCard(idCard);
                elderly.setBirthday(birthday);
                elderly.setAge(age);
            }

            elderly.setName(name);
            elderly.setCreateTime(new Date());
            elderly.setApplyStatus(1);
            elderly.setInstitutionCode(institutionCode);
            elderlyService.update(elderly);

            user.setName(name);
            user.setInstitutionCode(institutionCode);
            userService.update(user);


            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            insertErrorForAffair("/Elderly/Add",jsonObject,e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }
    }

    //编辑评估间隔时间
    @RequestMapping(value = "EditAssessSpanDay", method = RequestMethod.POST)
    public MyResult EditAssessSpanDay(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String elderlyCode = jsonObject.getString("elderlyCode");
            int assessSpanDay = jsonObject.getInteger("assessSpanDay");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/Add");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);
            elderly.setAssessSpanDay(assessSpanDay);
            elderlyService.update(elderly);

            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        } catch (Exception e) {
            insertErrorForAffair("/Elderly/Add",jsonObject,e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }
    }



    //后台编辑
    @RequestMapping(value = "Edit", method = RequestMethod.POST)
    @Transactional
    public MyResult Edit(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String areaCode = jsonObject.getString("areaCode");
            Integer elderlyType = jsonObject.getInteger("elderlyType");
            String lat = jsonObject.getString("lat");
            String lon = jsonObject.getString("lon");
            Integer sysNation = jsonObject.getInteger("nationId");
            String idCard = jsonObject.getString("idCard");
            Integer isMarriage = jsonObject.getInteger("isMarriage");
            Integer politicsStatus = jsonObject.getInteger("politicsStatus");
            Integer education = jsonObject.getInteger("education");
            Integer censusRegister = jsonObject.getInteger("censusRegister");
            String phone = jsonObject.getString("phone");
            String homeAddress = jsonObject.getString("homeAddress");
            Integer livingStatus = jsonObject.getInteger("livingStatus");
            String heardImg = jsonObject.getString("heardImg");
            String urgencyContact = jsonObject.getString("urgencyContact");
            String urgencyPhone = jsonObject.getString("urgencyPhone");
            Integer relation = jsonObject.getInteger("relation");
            Integer selfCardAbility = jsonObject.getInteger("selfCardAbility");
            Integer psychologyStatus = jsonObject.getInteger("psychologyStatus");
            Integer bloodType = jsonObject.getInteger("bloodType");
            String irritabilityMedicine = jsonObject.getString("irritabilityMedicine");
            Integer medicalSecurityStatus = jsonObject.getInteger("medicalSecurityStatus");
            String illness = jsonObject.getString("illness");
            Integer isOperation = jsonObject.getInteger("isOperation");
            String operationCause = jsonObject.getString("operationCause");
            Date operationTime = jsonObject.getDate("operationTime");
            Integer dietaryHabit = jsonObject.getInteger("dietaryHabit");
            Integer smokeStatus = jsonObject.getInteger("smokeStatus");
            Integer drinkStatus = jsonObject.getInteger("drinkStatus");
            String drinkKind = jsonObject.getString("drinkKind");
            String exerciseType = jsonObject.getString("exerciseType");
            Integer exerciseStatus = jsonObject.getInteger("exerciseStatus");
            Integer exerciseTime = jsonObject.getInteger("exerciseTime");
            Integer pocketbook = jsonObject.getInteger("pocketbook");
            String monthlyIncome = jsonObject.getString("monthlyIncome");
            String monthlyConsumption = jsonObject.getString("monthlyConsumption");
            String memberLevel = jsonObject.getString("memberLevel");
            String cardInsideCode = jsonObject.getString("cardInsideCode");
            String cardCoding = jsonObject.getString("cardCoding");
            String periodOfValidity = jsonObject.getString("periodOfValidity");
            Integer serviceStatus = jsonObject.getInteger("serviceStatus");
            String terminalCode = jsonObject.getString("terminalCode");
            JSONArray serviceDemand = jsonObject.getJSONArray("serviceDemand");
            String name = jsonObject.getString("name");
            String cardStatus = jsonObject.getString("cardStatus");
            Double cashPledge = jsonObject.getDouble("cashPledge");
            //Integer elderlyClass = jsonObject.getInteger("elderlyClass");
            //Integer status = jsonObject.getInteger("status");
            String zoneCode =jsonObject.getString("zoneCode");
            String elderlyClassCode =jsonObject.getString("elderlyClassCode");

            String elderlyCode = jsonObject.getString("elderlyCode");

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);
            if(elderly==null){
                return failed("该老人不存在！");
            }

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/Edit");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }



            Elderly elderly1 = elderlyService.getByPhone(phone);
            if (elderly1 != null) {
                if (!elderly1.getElderlyCode().equals(elderlyCode)) {
                    return failed("该手机号已注册！");
                }
            }

            Elderly elderly2 = elderlyService.getByIdCard(idCard);
            if (elderly2 != null) {
                if (!elderly2.getElderlyCode().equals(elderlyCode)) {
                    return failed("该身份证号已注册！");
                }
            }

            User user=userService.getByUserCode(elderly.getUserCode());
            User userByPhone = userService.getByPhone(phone);
            if (userByPhone != null) {
                if (!user.getUserCode().equals(userByPhone.getUserCode())) {
                    return failed("该手机号已注册！");
                }
            }

            if(areaCode==null||areaCode.equals("")){
                elderly.setAreaCode(null);
                elderly.setAreaName(null);
            }else {
                String areaName = getAreaName(areaCode, "");
                elderly.setAreaCode(areaCode);
                elderly.setAreaName(areaName);
            }


            if(zoneCode==null||zoneCode.equals("")){
                elderly.setZoneCode(null);
            }else {
                String zoneName =getZoneName(zoneCode,"");
                String zoneCodePath=getZoneCode(zoneCode,"");
                elderly.setZoneCode(zoneCode);
                elderly.setZoneName(zoneName);
                elderly.setZoneCodePath(","+zoneCodePath+",");
            }
            if (elderlyType == null || elderlyType.equals("")) {
                elderly.setElderlyType(0);
            } else {
                elderly.setElderlyType(elderlyType);
            }
            if (lat == null || lat.equals("")) {
                elderly.setLat(null);
            } else {
                elderly.setLat(lat);
            }
            if (lon == null || lon.equals("")) {
                elderly.setLon(null);
            } else {
                elderly.setLon(lon);
            }

            if(sysNation!=null){
                elderly.setSysNation(sysNation);

            }

            if (idCard == null || idCard.equals("")) {
                elderly.setIdCard(null);
                elderly.setGender(0);
            } else {
                int gender = GetGender(idCard);
                int age = GetAge(idCard);
                Date birthday = GetBirthday(idCard);
                elderly.setGender(gender);
                elderly.setIdCard(idCard);
                elderly.setBirthday(birthday);
                elderly.setAge(age);
            }
            if (isMarriage == null || isMarriage.equals("")) {
                elderly.setIsMarriage(0);
            } else {
                elderly.setIsMarriage(isMarriage);
            }
            if (politicsStatus == null || politicsStatus.equals("")) {
                elderly.setPoliticsStatus(0);
            } else {
                elderly.setPoliticsStatus(politicsStatus);
            }
            if (education == null || education.equals("")) {
                elderly.setEducation(0);
            } else {
                elderly.setEducation(education);
            }
            if (censusRegister == null || censusRegister.equals("")) {
                elderly.setCensusRegister(0);
            } else {
                elderly.setCensusRegister(censusRegister);
            }
            elderly.setPhone(phone);
            if (homeAddress == null || homeAddress.equals("")) {
                elderly.setHomeAddress(null);
            } else {
                elderly.setHomeAddress(homeAddress);
            }
            if (livingStatus == null || livingStatus.equals("")) {
                elderly.setLivingStatus(0);
            } else {
                elderly.setLivingStatus(livingStatus);
            }
            if (heardImg == null || heardImg.equals("")) {
                elderly.setHeardImg(null);
            } else {
                elderly.setHeardImg(heardImg);
            }
            if (urgencyContact == null || urgencyContact.equals("")) {
                elderly.setUrgencyContact(null);
            } else {
                elderly.setUrgencyContact(urgencyContact);
            }
            if (urgencyPhone == null || urgencyPhone.equals("")) {
                elderly.setUrgencyPhone(null);
            } else {
                elderly.setUrgencyPhone(phone);
            }
            if (relation == null || relation.equals("")) {
                elderly.setRelation(0);
            } else {
                elderly.setRelation(relation);
            }
            if (selfCardAbility == null || selfCardAbility.equals("")) {
                elderly.setSelfCardAbility(0);
            } else {
                elderly.setSelfCardAbility(selfCardAbility);
            }
            if (psychologyStatus == null || psychologyStatus.equals("")) {
                elderly.setPsychologyStatus(0);
            } else {
                elderly.setPsychologyStatus(psychologyStatus);
            }
            if (bloodType == null || bloodType.equals("")) {
                elderly.setBloodType(0);
            } else {
                elderly.setBloodType(bloodType);
            }
            if (irritabilityMedicine == null || irritabilityMedicine.equals("")) {
                elderly.setIrritabilityMedicine(null);
            } else {
                elderly.setIrritabilityMedicine(irritabilityMedicine);
            }
            if (medicalSecurityStatus == null || medicalSecurityStatus.equals("")) {
                elderly.setMedicalSecurityStatus(0);
            } else {
                elderly.setMedicalSecurityStatus(medicalSecurityStatus);
            }
            if (illness == null || illness.equals("")) {
                elderly.setIllness(null);
            } else {
                elderly.setIllness(illness);
            }
            if (isOperation == null || isOperation.equals("")) {
                elderly.setIsOperation(0);
            } else {
                elderly.setIsOperation(isOperation);
            }
            if (operationCause == null || operationCause.equals("")) {
                elderly.setOperationCause(operationCause);
            } else {
                elderly.setOperationCause(operationCause);
            }
            if (operationTime == null || operationTime.equals("")) {
                elderly.setOperationTime(null);
            } else {
                elderly.setOperationTime(operationTime);
            }
            if (dietaryHabit == null || dietaryHabit.equals("")) {
                elderly.setDietaryHabit(0);
            } else {
                elderly.setDietaryHabit(dietaryHabit);
            }
            if (smokeStatus == null || smokeStatus.equals("")) {
                elderly.setSmokeStatus(0);
            } else {
                elderly.setSmokeStatus(smokeStatus);
            }
            if (drinkStatus == null || drinkStatus.equals("")) {
                elderly.setDrinkStatus(0);
            } else {
                elderly.setDrinkStatus(drinkStatus);
            }
            if (drinkKind == null || drinkKind.equals("")) {
                elderly.setDrinkKind(null);
            } else {
                elderly.setDrinkKind(drinkKind);
            }
            if (exerciseType == null || exerciseType.equals("")) {
                elderly.setExerciseType(null);
            } else {
                elderly.setExerciseType(exerciseType);
            }
            if (exerciseStatus == null || exerciseStatus.equals("")) {
                elderly.setExerciseStatus(0);
            } else {
                elderly.setExerciseStatus(exerciseStatus);
            }
            if (exerciseTime == null || exerciseTime.equals("")) {
                elderly.setExerciseTime(0);
            } else {
                elderly.setExerciseTime(exerciseTime);
            }
            if (pocketbook == null || pocketbook.equals("")) {
                elderly.setPocketbook(0);
            } else {
                elderly.setPocketbook(pocketbook);
            }
            if (monthlyIncome == null || monthlyIncome.equals("")) {
                elderly.setMonthlyIncome(null);
            } else {
                elderly.setMonthlyIncome(monthlyIncome);
            }
            if (monthlyConsumption == null || monthlyConsumption.equals("")) {
                elderly.setMonthlyConsumption(null);
            } else {
                elderly.setMonthlyConsumption(monthlyConsumption);
            }
            if (memberLevel == null || memberLevel.equals("")) {
                elderly.setMemberLevel(null);
            } else {
                elderly.setMemberLevel(memberLevel);
            }
            if (cardInsideCode == null || cardInsideCode.equals("")) {
                elderly.setCardInsideCode(null);
            } else {
                elderly.setCardInsideCode(cardInsideCode);
            }
            if (cardCoding == null || cardCoding.equals("")) {
                elderly.setCardCoding(null);
            } else {
                elderly.setCardCoding(cardCoding);
            }
            if (periodOfValidity == null || periodOfValidity.equals("")) {
                elderly.setPeriodOfValidity(null);
            } else {
                elderly.setPeriodOfValidity(periodOfValidity);
            }
            if (serviceStatus == null || serviceStatus.equals("")) {
                elderly.setServiceStatus(0);
            } else {
                elderly.setServiceStatus(serviceStatus);
            }
            if (terminalCode == null || terminalCode.equals("")) {
                elderly.setTerminalCode(null);
            } else {
                elderly.setTerminalCode(terminalCode);
            }
            if (serviceDemand == null || serviceDemand.equals("")) {
                elderly.setServiceDemand(null);
            } else {
                elderly.setServiceDemand(serviceDemand.toString());
            }
            if (name == null || name.equals("")) {
                elderly.setName(null);
            } else {
                elderly.setName(name);
            }
            if (cardStatus == null || cardStatus.equals("")) {
                elderly.setCardStatus(null);
            } else {
                elderly.setCardStatus(cardStatus);
            }
            if (cashPledge == null || cashPledge.equals("")) {
                elderly.setCashPledge(0);
            } else {
                elderly.setCashPledge(cashPledge);
            }
            elderly.setElderlyClassCode(elderlyClassCode);
            elderlyService.update(elderly);


            user.setName(name);
            user.setLoginName(idCard);
            user.setPhone(phone);
            //user.setStatus(status);
            user.setPassword(getMD5Str(phone.substring(5,11)));
            userService.update(user);



            //update device user info
            String url = deviceApi+"/UserDevice/UpdateUserInfo";
            HashMap<String,Object> map=new HashMap<>();
            map.put("timeStr",timeStr);
            map.put("sign",sign);
            map.put("userCode",elderly.getUserCode());
            postTemplate(url, map);




            return success(elderly);
        } catch (Exception e) {
            insertErrorForAffair("/Elderly/Edit!",jsonObject,e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }
    }


    //政府管理员获取面板数据
    @RequestMapping(value = "Pannel", method = RequestMethod.POST)
    public MyResult Pannel(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");


            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/Pannel");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);
            String governmentCode = staff.getGovernmentCode();

            List<Elderly> listElderly = elderlyService.ListElderlyByGovernmentCode(governmentCode);
            List<Elderly> listElderlyMan = elderlyService.ListElderlyByGovernmentCodeMan(governmentCode);


            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("elderlyCount",listElderly.size());
            jsonObject1.put("elderlyCountMan",listElderlyMan.size());
            jsonObject1.put("elderlyCountWoman",listElderly.size()-listElderlyMan.size());

            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/Pannel", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //政府管理员获取面板数据
    @RequestMapping(value = "PannelVisual", method = RequestMethod.POST)
    public MyResult PannelVisual(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String governmentCode = jsonObject.getString("governmentCode");


            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/PannelVisual");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            List<Elderly> listElderly = elderlyService.ListElderlyByGovernmentCode(governmentCode);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("elderlyCount",listElderly.size());
            return success(jsonObject1);
        } catch (Exception e) {
            insertError("/Elderly/PannelVisual", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }







    //列表(for商家)
    @RequestMapping(value = "PageForBusiness", method = RequestMethod.POST)
    public MyResult PageForBusiness(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");


            String startTimeStr = jsonObject.getString("startTime");
            String endTimeStr = jsonObject.getString("endTime");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date startTime = sdf.parse(startTimeStr);
            Date endTime = sdf.parse(endTimeStr);

            String zoneCode = jsonObject.getString("zoneCode");

            String phone = jsonObject.getString("phone");
            String idCard = jsonObject.getString("idCard");

            String name = jsonObject.getString("name");

            String censusRegister1=jsonObject.getString("censusRegister");
            int censusRegister=-1;
            if(!censusRegister1.equals("")){
                censusRegister=Integer.parseInt(censusRegister1);
            }

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForBusiness");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Staff staff = staffService.getByStaffCode(staffCode);
            String governmentCode = staff.getGovernmentCode();


            Calendar calendar = new GregorianCalendar();
            calendar.setTime(endTime);
            calendar.add(calendar.DATE, 1); //把日期往后增加一天,整数  往后推,负数往前移动
            endTime = calendar.getTime(); //这个时间就是日期往后推一天的结果


            PageInfo<ElderlyDTO> pageInfoElderlyDTO = elderlyService.getSelectForGov(pageIndex, pageSize, startTime
                    , endTime, zoneCode, governmentCode, phone, idCard, name,censusRegister);
            List<ElderlyDTO> elderlyDTOList = pageInfoElderlyDTO.getList();
            for (ElderlyDTO elderlyDTO : elderlyDTOList) {
                SysNation sysNation = sysNationService.getById(elderlyDTO.getSysNation());
                if (sysNation == null) {
                    elderlyDTO.setNationNameDTO(null);
                } else {
                    elderlyDTO.setNationNameDTO(sysNation.getNation());
                }

                ElderlyDTO elderlyDTO1 = elderlyService.getByElderlyCode(elderlyDTO.getElderlyCode());
                elderlyDTO.setKinsfolkDTO(elderlyDTO1.getKinsfolkDTO());
                elderlyDTO.setServiceDemandDTO(elderlyDTO1.getServiceDemandDTO());
                User user = userService.getByUserCode(elderlyDTO.getUserCode());
                elderlyDTO.setUser(user);
                elderlyDTO.setUserPhone(user.getPhone());
            }

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("pageInfoElderlyDTO", pageInfoElderlyDTO);
            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Elderly/PageForBusiness", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    @RequestMapping(value = "GetElderly", method = RequestMethod.POST)
    public MyResult GetElderly(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            String elderlyCode = jsonObject.getString("elderlyCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/GetElderly");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            ElderlyDTO elderlyDTO = elderlyService.getByElderlyCode(elderlyCode);



            return success(elderlyDTO);
        } catch (Exception e) {
            insertError("/Elderly/GetElderly", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    @RequestMapping(value = "GetElderlyForApp", method = RequestMethod.POST)
    public MyResult GetElderlyForApp(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String userCode = jsonObject.getString("userCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/GetElderlyForApp");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            User user = userService.getByUserCode(userCode);
            if(user.getUserType() != 1){
                return failed("用户类型错误");
            }

            ElderlyDTO elderlyDTO = elderlyService.getByUserCode(userCode);
            elderlyDTO.setZoneCodePathName(getZoneName(elderlyDTO.getZoneCode(),""));

            return success(elderlyDTO);
        }
        catch (Exception e) {
            insertError("/Elderly/GetElderlyForApp", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "UpdateZoneForApp", method = RequestMethod.POST)
    public MyResult UpdateZoneForApp(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String userCode = jsonObject.getString("userCode");
            String zoneCode = jsonObject.getString("zoneCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/UpdateZoneForApp");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            User user = userService.getByUserCode(userCode);
            if(user.getUserType() != 1){
                return failed("用户类型错误");
            }

            Elderly elderly = elderlyService.getByUserCode(userCode);
            elderly.setZoneCode(zoneCode);
            elderly.setZoneName(zoneService.getByZoneCode(zoneCode).getName());
            elderly.setZoneCodePath(getZoneCode(zoneCode,""));
            elderlyService.update(elderly);


            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);
        }
        catch (Exception e) {
            insertError("/Elderly/UpdateZoneForApp", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    /**
     * 根据userCode查询所属的组织树信息,Device调用
     * @param jsonObject
     * @return
     */
    @RequestMapping(value = "GetElderlyZone", method = RequestMethod.POST)
    public MyResult GetElderlylist(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            String userCode = jsonObject.getString("userCode");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign, "/Elderly/GetElderlyZone");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            ElderlyDTO2 elderly = elderlyService.getElderlyList(userCode);
            return success(elderly);

        }catch (Exception e) {
        insertError("/Elderly/GetElderlyZone", jsonObject.toJSONString(), getExceptionMsg(e), "api");
        return anomalous(getExceptionMsg(e));
    }
    }

    //用户消费订单统计
    @RequestMapping(value = "GetConsumerUsers", method = RequestMethod.POST)
    public MyResult GetConsumerUsers(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String startTime = jsonObject.getString("startTime");
            String endTime = jsonObject.getString("endTime");
            String businessCode = jsonObject.getString("businessCode");
            int orderType = jsonObject.getIntValue("orderType");
            String name = jsonObject.getString("name");
            int pageIndex = jsonObject.getIntValue("pageIndex");
            int pageSize = jsonObject.getIntValue("pageSize");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/GetConsumerUsers");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            endTime=endTime+" 23:59:59";

            Staff staff = staffService.getByStaffCode(staffCode);

            PageInfo<ElderlyDTO> elderlyDTOPageInfo =
                    elderlyService.getForConsumerUsers(pageIndex, pageSize, staff.getGovernmentCode(),
                            businessCode, startTime, endTime, orderType, name);


            return success(elderlyDTOPageInfo);
        } catch (Exception e) {
            insertError("/Elderly/GetConsumerUsers", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "GetElderlyByPhone", method = RequestMethod.POST)
    public MyResult GetElderlyByPhone(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String phone = jsonObject.getString("phone");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/GetElderlyByPhone");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            ElderlyDTO elderlyDTO = elderlyService.getByPhone(phone);
            if(elderlyDTO!=null){
                User userCode = userService.getByUserCode(elderlyDTO.getUserCode());
                elderlyDTO.setUserName(userCode.getName());
                elderlyDTO.setUserPhone(userCode.getPhone());
                elderlyDTO.setUserStatus(userCode.getStatus());
            }
            return success(elderlyDTO);
        } catch (Exception e) {
            insertError("/Elderly/GetElderlyByPhone", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "PageForBusinessAdm", method = RequestMethod.POST)
    public MyResult PageForBusinessAdm(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");
            int status = jsonObject.getInteger("status");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/PageForBusinessAdm");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            Staff staff = staffService.getByStaffCode(staffCode);

            PageInfo<ElderlyDTO> elderlyDTOPageInfo = elderlyService.getListByGovernmentCode(pageIndex, pageSize, staff.getGovernmentCode(), name, phone,status);
            return success(elderlyDTOPageInfo);
        } catch (Exception e) {
            insertError("/Elderly/PageForBusinessAdm", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //给老人绑定IC卡
    @RequestMapping(value = "BindIcCard", method = RequestMethod.POST)
    @Transactional
    public MyResult BindIcCard(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String icCard = jsonObject.getString("icCard");
            String elderlyCode = jsonObject.getString("elderlyCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/BindIcCard");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            if (icCard.equals("")||icCard==null){
                return failed("IC卡号不能为空");
            }

            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);
            Elderly elderly1 = elderlyService.getByIcCard(icCard);

            if (elderly1!=null){
                return failed("此卡已被绑定");
            }

            CardStatus cardStatus = cardStatusService.getByCardNumber(icCard);
            if (cardStatus!=null){
                if (cardStatus.getStatus()==2){
                    return failed("此卡已被冻结");
                }
            }



            //将老卡废弃
            if (elderly.getIcCard()!=null){
                CardStatus cardStatus1 = cardStatusService.getByCardNumber(elderly.getIcCard());
                if (cardStatus1.getStatus()==1){
                    return failed("该用户已绑定过IC卡,请先挂失再从新绑定");
                }else {
                    cardStatus1.setStatus(3);
                    cardStatusService.update(cardStatus1);
                    CardRecord cardRecord=new CardRecord();
                    cardRecord.setCardRecordCode(UUID.randomUUID().toString());
                    cardRecord.setCardNumber(elderly.getIcCard());
                    cardRecord.setElderlyCode(elderlyCode);
                    cardRecord.setStaffCode(staffCode);
                    cardRecord.setCreateTime(new Date());
                    cardRecord.setContent("IC卡被废弃");
                    cardRecord.setGovernmentCode(staffService.getByStaffCode(staffCode).getGovernmentCode());
                    cardRecordService.insert(cardRecord);
                }
            }





            ElderlyDTO elderlyDTO = elderlyService.getByElderlyCode(elderlyCode);
            elderlyDTO.setIcCard(icCard);
            elderlyService.update(elderlyDTO);




            //从新绑定新卡
            if (cardStatus!=null){
                cardStatus.setStatus(1);
                cardStatusService.update(cardStatus);
            }else {
                cardStatus=new CardStatus();
                cardStatus.setCardStatusCode(UUID.randomUUID().toString());
                cardStatus.setCardNumber(icCard);
                cardStatus.setStatus(1);
                cardStatus.setGovernmentCode(staffService.getByStaffCode(staffCode).getGovernmentCode());
                cardStatusService.insert(cardStatus);
            }



            CardRecord cardRecord=new CardRecord();
            cardRecord.setCardRecordCode(UUID.randomUUID().toString());
            cardRecord.setCardNumber(icCard);
            cardRecord.setElderlyCode(elderlyCode);
            cardRecord.setStaffCode(staffCode);
            cardRecord.setCreateTime(new Date());
            cardRecord.setContent("IC卡被绑定");
            cardRecord.setGovernmentCode(staffService.getByStaffCode(staffCode).getGovernmentCode());
            cardRecordService.insert(cardRecord);

            JSONObject jsonObject1=new JSONObject();

            return success(jsonObject1);
        } catch (Exception e) {
            insertErrorForAffair("/Elderly/BindIcCard!",jsonObject,e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return anomalous(getExceptionMsg(e));
        }
    }

    //主动关怀页面
    @RequestMapping(value = "CarePage", method = RequestMethod.POST)
    public MyResult CarePage(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");
            Date startTime = jsonObject.getDate("startTime");
            String name = jsonObject.getString("name");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/CarePage");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            SimpleDateFormat format = new SimpleDateFormat("dd");
            if (startTime==null||startTime.equals("")){
                startTime=new Date();
            }

            int day=Integer.parseInt(format.format(startTime));

            SimpleDateFormat format1 = new SimpleDateFormat("MM");

            int month=Integer.parseInt(format1.format(startTime));


            Staff staff = staffService.getByStaffCode(staffCode);

            PageInfo<ElderlyDTO> elderlyDTOPageInfo = elderlyService.getCarePage(pageIndex, pageSize, staff.getGovernmentCode(), name, month, day);

            return success(elderlyDTOPageInfo);
        } catch (Exception e) {
            insertError("/Elderly/CarePage", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //根据IC卡号活得老人姓名
    @RequestMapping(value = "GetByIcCard", method = RequestMethod.POST)
    public MyResult GetByIcCard(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");
            String icCard = jsonObject.getString("icCard");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/GetByIcCard");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            Elderly elderly = elderlyService.getByIcCard(icCard);

            if (elderly==null){
                return failed("此卡查询不到老人信息");
            }

            return success(elderly);
        } catch (Exception e) {
            insertError("/Elderly/GetByIcCard", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //一键求助获取号码
    @RequestMapping(value = "GetHelpPhone", method = RequestMethod.POST)
    public MyResult GetHelpPhone(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");





            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/GetHelpPhone");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            User user = userService.getByUserCode(userCode);
            Seats seats = seatsService.getByGovernmentCode(user.getGovernmentCode());

            if (seats==null){
                return failed("该代理商没有申请主叫号码");
            }

            return success(seats.getCallingPhone());
        } catch (Exception e) {
            insertError("/Elderly/GetHelpPhone", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //查询老人余额
    @RequestMapping(value = "GetElderlyBalance", method = RequestMethod.POST)
    public MyResult GetElderlyBalance(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");


            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/GetElderlyBalance");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            ElderlyDTO elderlyDTO = elderlyService.getByUserCode(userCode);

            return success(elderlyDTO.getBalance());
        } catch (Exception e) {
            insertError("/Elderly/GetElderlyBalance", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //老人打卡
    @RequestMapping(value = "Clockin", method = RequestMethod.POST)
    public MyResult Clockin(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");

            String elderlyCode = jsonObject.getString("elderlyCode");
            String imgPath = jsonObject.getString("imgPath");
            String lon = jsonObject.getString("lon");
            String lat = jsonObject.getString("lat");
            String address = jsonObject.getString("address");
            String remark = jsonObject.getString("remark");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/Clockin");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            Serve serve = serveService.getByUserCode(userCode);
            User user = userService.getByUserCode(userCode);
            Elderly elderly = elderlyService.getByElderlyCode(elderlyCode);



            ElderlyClockin elderlyClockin = new ElderlyClockin();
            elderlyClockin.setElderlyClockinCode(UUID.randomUUID().toString());
            elderlyClockin.setGovernmentCode(user.getGovernmentCode());
            elderlyClockin.setElderlyCode(elderlyCode);
            elderlyClockin.setImgUrl(imgPath);
            elderlyClockin.setLat(lat);
            elderlyClockin.setLon(lon);
            elderlyClockin.setAddress(address);
            elderlyClockin.setCreateTime(new Date());
            elderlyClockin.setRemark(remark);
            elderlyClockin.setServeCode(serve.getServeCode());
            elderlyClockin.setIdCard(elderly.getIdCard());
            elderlyClockin.setZoneCodePath(elderly.getZoneCodePath());
            elderlyClockin.setZoneCode(elderly.getZoneCode());
            elderlyClockinService.insert(elderlyClockin);


            //更新打卡时间
            elderly.setLastDateClockin(new Date());
            elderlyService.update(elderly);


            //添加打卡月份
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            String date1 = sdf.format(new Date());
            Date date = sdf.parse(date1);
            ElderlyClockinMonth elderlyClockinMonth = elderlyClockinMonthService.getByElderlyCodeMonth(elderlyCode, date);
            if(elderlyClockinMonth == null){
                elderlyClockinMonth = new ElderlyClockinMonth();
                elderlyClockinMonth.setElderlyClockinMonthCode(UUID.randomUUID().toString());
                elderlyClockinMonth.setElderlyCode(elderlyCode);
                elderlyClockinMonth.setMonth(date);
                elderlyClockinMonthService.insert(elderlyClockinMonth);
            }


            JSONObject jsonObject1 = new JSONObject();
            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Elderly/Clockin", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //服务端查询老人
    @RequestMapping(value = "GetElderlyDTOByApp", method = RequestMethod.POST)
    public MyResult GetElderlyDTOByApp(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String userCode = jsonObject.getString("userCode");
            String zoneCode = jsonObject.getString("zoneCode");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");

            PreCheck preCheck = checkSignFrontInterface(timeStr, sign,"/Elderly/GetElderlyDTOByApp");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }
            User user = userService.getByUserCode(userCode);
            String governmentCode = user.getGovernmentCode();


            PageInfo<ElderlyDTO> elderlyDTOPageInfo = elderlyService.getElderlyDTOByAppNew(pageIndex, pageSize, zoneCode, governmentCode, name, phone);
            return success(elderlyDTOPageInfo);

        } catch (Exception e) {
            insertError("/Elderly/GetElderlyDTOByApp", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }





    public String getZoneName(String zoneCode, String zoneName) {
        Zone zone = zoneService.getByZoneCode(zoneCode);
        if (zone != null) {
            if (zoneName == "") {
                zoneName = zone.getName();
            } else {
                zoneName = zone.getName() + "," + zoneName;
            }
            zoneName = getZoneName(zone.getParentZoneCode(), zoneName);
        }
        return zoneName;
    }

    public String getZoneCode(String zoneCode, String zoneCode1) {
        Zone zone = zoneService.getByZoneCode(zoneCode);
        if (zone != null) {
            if (zoneCode1 == "") {
                zoneCode1 = zone.getZoneCode();
            } else {
                zoneCode1 = zone.getZoneCode() + "," + zoneCode1;
            }
            zoneCode1 = getZoneCode(zone.getParentZoneCode(), zoneCode1);
        }
        return zoneCode1;
    }


    public String getAreaName(String areaCode, String areaName) {
        Area area = areaService.getByAreaCode(areaCode);
        if (area != null) {
            if (areaName == "") {
                areaName = area.getName();
            } else {
                areaName = area.getName() + "," + areaName;
            }
            areaName = getAreaName(area.getParentAreaCode(), areaName);
        }
        return areaName;
    }

    //判断年龄
    public int GetAge(String idCard) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        String nowTime = simpleDateFormat.format(date);
        String nowTimeNumber = nowTime.substring(0, 4);
        int nowTimeNum = Integer.parseInt(nowTimeNumber);
        String ageNumber = idCard.substring(6, 10);
        int ageNum = Integer.parseInt(ageNumber);
        return nowTimeNum - ageNum;
    }

    //判断生日
    public Date GetBirthday(String idCard) {
        String ageNumber = idCard.substring(6, 10);     //年
        String ageNumber1 = idCard.substring(10, 12);     //月
        String ageNumber2 = idCard.substring(12, 14);     //日
        String birthday1 = ageNumber + "-" + ageNumber1 + "-" + ageNumber2;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date birthday = null;
        try {
            simpleDateFormat.setLenient(false);
            birthday = simpleDateFormat.parse(birthday1);

        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("身份证号不合法");
        }

        return birthday;
    }

    //判断性别
    public int GetGender(String idCard) {
        String genderNumber = idCard.substring(16, 17); //倒数第二位
        int genderNum = Integer.parseInt(genderNumber);
        int gender;
        if (genderNum % 2 == 0) {
            gender = 0;
        } else {
            gender = 1;
        }
        return gender;
    }


    @RequestMapping(value = "PageToGovPlatform", method = RequestMethod.POST)
    public MyResult PageForGov(@RequestBody JSONObject jsonObject) {
        try {
            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");
            int status = jsonObject.getInteger("status");
            String name = jsonObject.getString("name");
            String phone = jsonObject.getString("phone");
            String governmentCode = jsonObject.getString("governmentCode");
            PageInfo<ElderlyDTO> elderlyDTOPageInfo = elderlyService.getListByGovernmentCode(pageIndex, pageSize, governmentCode, name, phone,status);
            return success(elderlyDTOPageInfo);
        } catch (Exception e) {
            insertError("/Elderly/PageToGovPlatform", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }


    //查询充值老人
    @RequestMapping(value = "GetRechargeElderly", method = RequestMethod.POST)
    public MyResult GetRechargeElderly(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/GetRechargeElderly");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");
            String phone = jsonObject.getString("phone");
            String name = jsonObject.getString("name");
            String zoneCode = jsonObject.getString("zoneCode");
            int elderlyClass = jsonObject.getInteger("elderlyClass");
            int censusRegister = jsonObject.getInteger("censusRegister");

            if (zoneCode == null) {
                zoneCode = "00000000-0000-0000-0000-000000000000";
            }


            Staff staff = staffService.getByStaffCode(staffCode);
            String governmentCode = staff.getGovernmentCode();

            PageInfo<ElderlyDTO> elderlyDTOPageInfo = elderlyService.getRechargeElderly(pageIndex,
                    pageSize, zoneCode, phone, governmentCode, name, censusRegister,elderlyClass);
            List<ElderlyDTO> elderlyDTOList = elderlyDTOPageInfo.getList();
            for (ElderlyDTO elderlyDTO : elderlyDTOList) {
                ElderlyClass elderlyClass1 = elderlyClassService.getByValue(elderlyDTO.getElderlyClass(), governmentCode);
                if (elderlyClass1!=null){
                    elderlyDTO.setAddBalance(elderlyClass1.getAddBalance());
                }
                User user = userService.getByUserCode(elderlyDTO.getUserCode());
                elderlyDTO.setUserPhone(user.getPhone());
            }

            return success(elderlyDTOPageInfo);
        } catch (Exception e) {
            insertError("/Elderly/GetRechargeElderly", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    //查询指定时间的新创建老人的充值消费金额
    @RequestMapping(value = "GetElderlyNewCard", method = RequestMethod.POST)
    public MyResult GetElderlyNewCard(@RequestBody JSONObject jsonObject) {


        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String staffCode = jsonObject.getString("staffCode");

            PreCheck preCheck = checkSignAdmInterface(timeStr, sign, staffCode,"/Elderly/GetElderlyNewCard");
            if (preCheck.getError() == 1) {
                return failed(preCheck.getMessage());
            }

            String name = jsonObject.getString("name");
            String idCard = jsonObject.getString("idCard");
            String phone = jsonObject.getString("phone");
            int elderlyClass = jsonObject.getInteger("elderlyClass");
            String zoneCode = jsonObject.getString("zoneCode");
            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");
            String startTimeStr = jsonObject.getString("startTime");
            String endTimeStr = jsonObject.getString("endTime");

            if (startTimeStr == null || startTimeStr.equals("")) {
                startTimeStr = "2019-01-01";
            }
            if (endTimeStr == null || endTimeStr.equals("")) {
                endTimeStr = "2030-01-01";
            }


            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date startTime = sdf.parse(startTimeStr);
            Date endTime = sdf.parse(endTimeStr);

            Calendar calendar = new GregorianCalendar();
            calendar.setTime(endTime);
            calendar.add(calendar.DATE, 1); //把日期往后增加一天,整数  往后推,负数往前移动
            endTime = calendar.getTime(); //这个时间就是日期往后推一天的结果

            Staff staff = staffService.getByStaffCode(staffCode);
            String governmentCode = staff.getGovernmentCode();
//            查询所有人金额的总数
            List<ElderlyDTO> elderlyList = elderlyService.getByElderly(name,idCard,phone,elderlyClass,zoneCode,governmentCode,startTime,endTime);
            double balanceAlltotal=0;
            double addBalancetotal=0;
            double payMonthtotal=0;

            for (ElderlyDTO elderlyDTO : elderlyList) {
                String elderlyCode = elderlyDTO.getElderlyCode();
//                String userCode = elderlyDTO.getUserCode();
                double addBalance = 0;
                double payMonth = 0;
                List<Recharge> rechargeList = rechargeService.getAddBalance(elderlyCode,startTime,endTime);
                for (Recharge recharge : rechargeList) {
                    addBalance+=recharge.getAddBalance();
                }
                List<Order> orderList = orderService.getOrderCreateTime(elderlyCode,startTime,endTime);
                for (Order order : orderList) {
                    payMonth+=order.getPrice();
                }
                addBalancetotal+=addBalance;
                payMonthtotal+=payMonth;
                balanceAlltotal+=addBalance-payMonth;
            }

//            列表
            PageInfo<ElderlyDTO> elderlyDTOPageInfo = elderlyService.getNewElderly(pageIndex,pageSize,name,idCard,phone,elderlyClass,zoneCode,governmentCode,startTime,endTime);
            List<ElderlyDTO> list = elderlyDTOPageInfo.getList();
            for (ElderlyDTO elderlyDTO : list) {
                String elderlyCode = elderlyDTO.getElderlyCode();
//                String userCode = elderlyDTO.getUserCode();
                double addBalance = 0;
                double payMonth = 0;
                List<Recharge> rechargeList = rechargeService.getAddBalance(elderlyCode,startTime,endTime);
                for (Recharge recharge : rechargeList) {
                    addBalance+=recharge.getAddBalance();
                }
                List<Order> orderList = orderService.getOrderCreateTime(elderlyCode,startTime,endTime);
                for (Order order : orderList) {
                    payMonth+=order.getPrice();
                }
                double balanceAll=addBalance-payMonth;
                elderlyDTO.setAddBalance(addBalance);
                elderlyDTO.setPayMonth(payMonth);
                elderlyDTO.setBalanceAll(balanceAll);
                elderlyDTO.setAddBalancetotal(addBalancetotal);
                elderlyDTO.setPayMonthtotal(payMonthtotal);
                elderlyDTO.setBalanceAlltotal(balanceAlltotal);
                }
            return success(elderlyDTOPageInfo);
        } catch (Exception e) {
            insertError("/Elderly/GetElderlyNewCard", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }

    @RequestMapping(value = "CarePageToGovPlatform", method = RequestMethod.POST)
    public MyResult CarePageToGovPlatform(@RequestBody JSONObject jsonObject) {
        try {

            int pageIndex = jsonObject.getInteger("pageIndex");
            int pageSize = jsonObject.getInteger("pageSize");
            Date startTime = jsonObject.getDate("startTime");
            String name = jsonObject.getString("name");
            String governmentCode = jsonObject.getString("governmentCode");


            SimpleDateFormat format = new SimpleDateFormat("dd");
            if (startTime==null||startTime.equals("")){
                startTime=new Date();
            }

            int day=Integer.parseInt(format.format(startTime));

            SimpleDateFormat format1 = new SimpleDateFormat("MM");

            int month=Integer.parseInt(format1.format(startTime));



            PageInfo<ElderlyDTO> elderlyDTOPageInfo = elderlyService.getCarePage(pageIndex, pageSize, governmentCode, name, month, day);

            return success(elderlyDTOPageInfo);
        } catch (Exception e) {
            insertError("/Elderly/CarePageToGovPlatform", jsonObject.toJSONString(), getExceptionMsg(e), "api");
            return anomalous(getExceptionMsg(e));
        }
    }






    //接口导入
    @RequestMapping(value = "AddForOut", method = RequestMethod.POST)
    public MyResult AddForOut(@RequestBody JSONObject jsonObject) {
        try {
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");

            JSONArray elderlyArray = jsonObject.getJSONArray("elderlyArray");
            String institutionCode = jsonObject.getString("institutionCode");

            if (!checkSignForOut(timeStr, sign)) {
                return failed("签名错误");
            }

            Institution institution = institutionService.getByInstitutionCode(institutionCode);


            HashMap<String,String> hashMapPhone = new HashMap<>();
            HashMap<String,String> hashMapIdCard = new HashMap<>();
            for(int i=0;i<elderlyArray.size();i++){

                String name = elderlyArray.getJSONObject(i).getString("name").trim();
                String phone = elderlyArray.getJSONObject(i).getString("phone").trim();
                String idCard = elderlyArray.getJSONObject(i).getString("idCard").trim();

                if(!phone.equals("") && phone.length() !=11){
                    return failed("手机号格式错误"+phone);
                }
                if(phone.equals("")){
                    phone = getPhoneAuto(hashMapPhone);
                }


                if(hashMapPhone.containsKey(phone)){
                    return failed("手机号存在重复的"+phone);
                }else{
                    hashMapPhone.put(phone,phone);
                }
                if(hashMapIdCard.containsKey(idCard)){
                    return failed("身份证号存在重复的"+idCard);
                }else{
                    hashMapIdCard.put(idCard,phone);
                }

                if(name.equals("")){
                    return failed("名称不能为空");
                }
                if(!isPhone(phone)){
                    return failed("手机格式错误");
                }
                if(!isIdCard(idCard)){
                    return failed("身份证格式错误");
                }

                User user = userService.getByPhone(phone);
                if(user != null){
                    return failed("手机号已使用："+phone);
                }

                Elderly elderly = elderlyService.getByIdCard(idCard);
                if(elderly != null){
                    return failed("身份证已使用："+idCard);
                }

            }

            Date date = new Date();
            for(int i=0;i<elderlyArray.size();i++){

                String name = elderlyArray.getJSONObject(i).getString("name");
                //String phone = elderlyArray.getJSONObject(i).getString("phone");
                String idCard = elderlyArray.getJSONObject(i).getString("idCard").trim();
                String lon = elderlyArray.getJSONObject(i).getString("lon");
                String lat = elderlyArray.getJSONObject(i).getString("lat");
                String address = elderlyArray.getJSONObject(i).getString("address");

                String phone = hashMapIdCard.get(idCard);

                User user = new User();
                user.setUserCode(UUID.randomUUID().toString());
                user.setPhone(phone);
                user.setLoginName(phone);
                user.setPassword(getMD5Str(phone.substring(5, 11)));
                user.setName(name);
                user.setCreateTime(date);
                user.setStatus(1);
                user.setUserType(1);
                user.setGovernmentCode(institution.getGovernmentCode());
                user.setInstitutionCode(institutionCode);
                userService.insert(user);

                Elderly elderly = new Elderly();
                elderly.setElderlyCode(UUID.randomUUID().toString());
                elderly.setUserCode(user.getUserCode());

                elderly.setLat(lat);
                elderly.setLon(lon);
                elderly.setHomeAddress(address);

                if (idCard == null || idCard.equals("")) {
                    elderly.setIdCard(null);
                    elderly.setGender(0);
                } else {
                    int gender = GetGender(idCard);
                    int age = GetAge(idCard);
                    Date birthday = GetBirthday(idCard);
                    elderly.setGender(gender);
                    elderly.setIdCard(idCard);
                    elderly.setBirthday(birthday);
                    elderly.setAge(age);
                }

                elderly.setPhone(phone);
                elderly.setName(name);
                elderly.setCreateTime(date);
                elderly.setGovernmentCode(institution.getGovernmentCode());
                elderly.setInstitutionCode(institutionCode);
                elderly.setApplyStatus(4);
                elderlyService.insert(elderly);

            }

            JSONObject jsonObject1 =new JSONObject();
            return success(jsonObject1);

        } catch (Exception e) {
            insertError("/Elderly/AddForOut",jsonObject.toJSONString(),getExceptionMsg(e),"api");
            return anomalous(getExceptionMsg(e));
        }
    }




    //生成登陆手机号
    private String getPhoneAuto(HashMap<String,String> hashMapPhone){

        String newPhone = "100"+random8();

        if(hashMapPhone.containsKey(newPhone)){
            newPhone = getPhoneAuto(hashMapPhone);
        }

        User user = userService.getByPhone(newPhone);
        if(user != null){
            newPhone = getPhoneAuto(hashMapPhone);
        }

        return newPhone;
    }

    /**
     * * 生成8位随机数
     **/
    private int random8() {
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        int[] c = new int[8];
        for (int i = 0; i < 8; i++) {
            c[i] = r.nextInt(9) + 1;
            sb.append(c[i]);
        }
        return Integer.parseInt(sb.toString());
    }


    //获取信息
    @RequestMapping(value = "InfoByIdCard",method = RequestMethod.POST)
    public MyResult InfoByIdCard(@RequestBody JSONObject jsonObject) {

        try{
            String timeStr = jsonObject.getString("timeStr");
            String sign = jsonObject.getString("sign");
            String idCard = jsonObject.getString("idCard").trim();

            if (!checkSignForOut(timeStr, sign)) {
                return failed("签名错误");
            }

            Elderly elderly = elderlyService.getByIdCard(idCard);

            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("elderly",elderly);

            return success(jsonObject1);
        }catch (Exception e){
            insertErrorForAffair("/Institution/Info",jsonObject,e);
            return anomalous(getExceptionMsg(e));
        }

    }



}
